package com.tm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.tm.mapper.RoleMapper;


import com.tm.model.Permission;
import com.tm.model.Person;
import com.tm.model.Role;
import com.tm.service.RoleService;
import com.tm.vo.RoleVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    RoleMapper roleMapper;


    @Override
    public RoleVo queryAllRole(RoleVo roleVo) {
        //查询总条数
        Integer  count  = roleMapper.queryRoleCount(roleVo);
        //将总条数赋值给工具类
        roleVo.setTotalCount(count);
        //上一步结束，得到分页的条件和所有条件查询，
        List<Role> list = roleMapper.queryRole(roleVo);
        roleVo.setList(list);
        return roleVo;
    }



    @Override
    public void updateRole(Role role) {
        Date data = new Date();
        role.setUpdateDate(data);
        roleMapper.updateById(role);
    }

    //新增
    @Override
    public void addRole(Role role) {
        Date data = new Date();
        role.setCreateDate(data);
        role.setUpdateDate(data);
        roleMapper.insert(role);

    }

    @Override
    public void deleteRoleId(Integer id) {
        roleMapper.deleteById(id);
    }

    //回显
    @Override
    public Role queryRoleById(Integer id) {
        return roleMapper.selectById(id);
    }
    @Override
    public void statusChange(Integer id, Integer status) {
        roleMapper.statusChange(id,status);
    }

    @Override
    public void exportFile(HttpServletResponse response) {
        List<Role> permissions = roleMapper.selectList(null);
        String fileName = "C:\\Users\\Administrator\\Desktop\\角色信息.xlsx";
        EasyExcel.write(fileName, Role.class).sheet().doWrite(permissions);
    }
    @Override
    public void uploadFile(MultipartFile dataFile) {
        ArrayList<Role> roles = new ArrayList<>();
        try {
            InputStream inputStream = dataFile.getInputStream();
            EasyExcel.read(inputStream, Person.class, new AnalysisEventListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {
                    roles.add((Role) o);
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    System.out.println("读取成功");
                }
            }).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        roles.forEach(role -> {
            roleMapper.insert(role);
        });
    }
}
